from apps.MarkManagement.view.common import *
from random import uniform
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sn
import time
import os

class AnalyzeClass(viewsets.ViewSet):
    def analysis_report(self, request):
        ## 从数据库获取数据
        # selected_titleGroupId = request.GET.get('titleGroupId')  # 用户选择的大项，后面再用
        classId = request.data['lessonId']  # 用户选择的课程
        # classId = request.GET.get('classInfo')
        lessonId = list(ClassInfo.objects.filter(id=classId).values())[0]['lesson_id']

        # 根据lessonId筛选大项
        titleGroup = list(TitleGroup.objects.filter(lesson=lessonId).values())

        # 取出大项的id和权重
        groupInfo = {}
        three_weights = {} # 三项计分的大项的权重
        three = ['平时', '期中', '期末', '实验']
        ids = {}
        for i in titleGroup:
            if i['name'] in three:
                three_weights.update({i['name']: float(i['weight'] / 100)})
            if i['name'] == '平时':
                ids['平时'] = i['id']
            if i['name'] == '期中':
                ids['期中'] = i['id']
            if i['name'] == '期末':
                ids['期末'] = i['id']
            groupInfo.update({i['id']: i['weight']})
        final = {} # 学生分数罗列
        title_avg = {} # 平时+期中成绩罗列
        mid_term = 0 # 以下是三个平均分
        last = 0
        normal = 0


        ids_mid = [] # 大项“期中”包含的小项id
        if '期中' in list(ids.keys()):
            for i in list(Title.objects.filter(titleGroup=ids['期中']).values()):
                ids_mid.append(i['id'])
        ids_final = []
        if '期末' in list(ids.keys()):
            for i in list(Title.objects.filter(titleGroup=ids['期末']).values()):
                ids_final.append(i['id'])
        ids_normal = []
        if '平时' in list(ids.keys()):
            for i in list(Title.objects.filter(titleGroup=ids['平时']).values()):
                ids_normal.append(i['id'])

        for i in groupInfo.keys():
            # 根据大项id筛选小项，关系为一对多
            titles = list(Title.objects.filter(titleGroup=i).values())
            # 取出小项的id和权重

            for n in titles:
                avg = 0
                # 根据小项id筛选出分数
                points = list(Point.objects.filter(title=n['id'], classInfo=classId).values())
                # 计算出每个学生在该课程对应的每个小项的成绩
                final_score = {}
                for p in points:
                    point = float(p['pointNumber'])
                    avg += point
                    if n['id'] in final_score:
                        final_score[n['id']].update({p['student_id']: point})
                    else:
                        final_score[n['id']] = dict({p['student_id']: point})
                if len(points) > 0:
                    avg /= len(points)
                final.update(final_score)
                # 获取平时数据
                if n['id'] in ids_normal and avg > 20:
                    normal += avg * float(n['weight'] / 100)
                    title_name = list(Title.objects.filter(id=n['id']).values())[0]['name']
                    title_avg.update({title_name: round(avg, 2)})
                # 获取期中数据
                if n['id'] in ids_mid and avg > 20:
                    mid_term += avg * float(n['weight'] / 100) # 乘以权重
                    title_name = list(Title.objects.filter(id=n['id']).values())[0]['name']
                    title_avg.update({title_name: round(avg, 2)})
                # 获取期末成绩
                if n['id'] in ids_final and avg > 20:
                    last += avg * float(n['weight'] / 100)
        # 总评成绩
        w1, w2, w3 = 0, 0, 0
        if '平时' in list(three_weights.keys()):
            w1 = three_weights['平时']
        if '期中' in list(three_weights.keys()):
            w2 = three_weights['期中']
        if '期末' in list(three_weights.keys()):
            w3 = three_weights['期末']
        overral_score = normal * w1 + mid_term * w2 + last * w3
        print(overral_score)

        #  文字总结
        # path = os.path.dirname(os.path.abspath(__file__))
        # t = pd.read_csv("\\root\\MarkSystem\\apps\\MarkManagement\\view\\template.csv")
        path = os.path.dirname(__file__)
        t = pd.read_csv(path + "/template.csv")
        temp = dict(zip(t['分段'], t['文字']))

        final_report = []
        report = ''
        ## 过程考核
        report += '      '
        report += temp['陈述1']
        report += temp['平时成绩_罗列']
        avgs = list(title_avg.values())
        for i in range(len(avgs)):
            report += str(avgs[i]) + ', '

        if len(avgs) > int(temp['平时作业量_阈值']):
            report += temp['平时作业量_偏大'].split(';')[0]
        else:
            report += temp['平时作业量_适中'].split(';')[0]

        report += temp['综述2'].split(';')[0]

        if mid_term > 0:
            report += temp['期中成绩_陈述']
            report += str(round(mid_term, 2))
            report += '。'
            if title_avg['期中考试'] <= float(temp['期中成绩_阈值']):
                report += temp['期中成绩_低']
            else:
                report += temp['期中成绩_高']

        final_report.append(report)
        report = ''

        ##总评成绩
        report += temp['陈述2']
        for i in list(three_weights.items()):
            report += i[0]
            report += ': '
            report += str(i[1])
            report += ', '

        if last > 0:
            if last >= float(temp['期末成绩_阈值']):
                report += temp['期末成绩_高']

            report += temp['陈述3']
            report += str(round(last, 2))
            report += ','

            report += temp['陈述4']
            report += str(round(overral_score, 2))
            report += '。'

        final_report.append(report)
        # 封装
        subjects = dict({'report': final_report,
                         })

        result = {
            'code': '2000',
            'subjects': subjects,
        }
        return JsonResponse(result, safe=False)





